<template>
  <div class="default">
    <div class="flex" style="justify-content: space-between;position: relative">
      <div class="flex" style="margin-right: 20px">
        <div class="search">模版名称：
          <el-input v-model="params.templateName" placeholder="请输入任务模版名称" style="width:200px" size="small"
                    prefix-icon="el-icon-search">
          </el-input>
        </div>
        <div class="search">品牌：
          <el-select size="small" v-model="params.brandPartyId" filterable>
            <el-option v-for="item in brandList" :value="item.id" :label="item.brandPartyName"
                       :key="item.id"></el-option>
          </el-select>
        </div>
        <!--        <div class="search">所属公司：-->
        <!--          <el-input v-model="params.companyName" placeholder="请输入公司名称" style="width:200px" size="small"-->
        <!--                    prefix-icon="el-icon-search">-->
        <!--          </el-input>-->
        <!--        </div>-->
        <div>
          <el-button type="primary" size="small" style="margin-left:10px;" @click="getModules" icon="el-icon-search">
            查询
          </el-button>
          <el-button
              size="small"
              style="
                margin-left: 10px;
                background-color: #303e9d;
                color: #eeeeee;
              "
              @click="_reset"
              icon="el-icon-refresh"
          >重置
          </el-button>
        </div>
      </div>
    </div>
    <div style="margin-bottom: 10px">
      <el-button type="primary" size="small" @click="taskListDialog" v-if="authorityList.includes(201)">任务列表
      </el-button>
      <el-button type="primary" size="small " @click="createdTemplate" v-if="authorityList.includes(202)">创建模版
      </el-button>
    </div>
    <el-table :data="dataList" border stripe :cell-style="{ 'textAlign': 'center' }" height="calc(100vh - 280px)"
              :header-cell-style="{  'fontSize': '14px', 'background-color': '#F3F6FD', 'color': '#333333', 'textAlign': 'center' }">
      <el-table-column
          type="index"
          label="序号"
          width="50">
      </el-table-column>
      <el-table-column prop="templateName" label="模版名称"></el-table-column>
      <el-table-column prop="day" label="任务周期">
        <template v-slot:default="scope">
          <span>{{ scope.row.day }}/天</span>
        </template>
      </el-table-column>
      <el-table-column label="模版类型">
        <template v-slot:default="scope">
          <span>{{ typeMap[scope.row.supplierType] || '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模板详情" width="600px">
        <template slot-scope="scope">
          <el-table :data="scope.row.taskList" max-height="200px"
                    v-loading="loading"
                    :header-cell-style="{  'fontSize': '14px', 'background-color': '#F3F6FD', 'color': '#333333', 'textAlign': 'center' }">
            <el-table-column prop="name" label="时间" width="100px" fixed="left"></el-table-column>
            <el-table-column label="任务">
              <template slot-scope="scope">
                <div style="float: left;margin-right: 10px" v-for="item in scope.row.task">{{ item.taskName }}</div>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column prop="brandPartyName" label="所属品牌方" width="200px"></el-table-column>
      <el-table-column prop="userName" label="创建人" width="150px"></el-table-column>
      <el-table-column prop="updateTime" label="创建时间" width="200px"></el-table-column>
      <el-table-column label="操作" width="200px">
        <template slot-scope="scope">
          <!--          <el-link type="danger" style="margin-right: 10px">删除</el-link>-->
          <el-link style="color: #303e9d" @click="editModules(scope.row)" v-if="authorityList.includes(203)">编辑
          </el-link>
          <el-link style="color: #303e9d;margin-left: 15px" @click="copyModules(scope.row)"
                   v-if="authorityList.includes(204)">复制模板
          </el-link>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="padding: 20px 0;" align="center" @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 30, 40, 50]"
                   layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
    </el-pagination>
    <!--    创建模版弹窗--><!--    创建模版弹窗--><!--    创建模版弹窗--><!--    创建模版弹窗--><!--    创建模版弹窗--><!--    创建模版弹窗-->
    <el-dialog :title="title+'模版'" :visible.sync="templateStatus" width="50%" center top="50px">
      <div v-if="title=='创建'" style="display: flex;margin-bottom: 10px;justify-content: space-between">
        <div :class="chooseDateIndex==item.type?'active':''" class="typeList"
             @click="chooseType(item.type)"
             v-for="item in taskNameList"><span>{{ item.name }}</span>
        </div>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 15px">
        <span style="width: 80px;">模版名称：</span>
        <el-input v-model="templateName" style="width: 80%" size="small" placeholder="请输入需要添加的任务名称"></el-input>
        <el-link style="color: #FEA523;margin-left: 15px" @click="pasteModules"
        >粘贴模板
        </el-link>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 15px">
        <span style="width: 80px;">预计工期：</span>
        <el-input v-model="day" style="width: 80%" size="small" placeholder="请输入完成本次任务的周期时间"><a slot="suffix"
                                                                                                style="height: 40px;line-height: 30px">天</a>
        </el-input>
      </div>
      <div style="display: flex;align-items: center;">
        <el-link @click="addTemplateName(templateCreateInfo)" type="primary" style="margin-bottom: 5px">+新增单条任务
        </el-link>
      </div>
      <div style="height: 500px;overflow-y: scroll">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane :label="v.name" :name="v.name" v-for="(v, i) in templateCreateInfo" :key="v.name">
            <span slot="label">{{ v.name }}<i class="el-icon-delete" style="margin-left: 5px"
                                              @click="deleteDate(i)"></i></span>
            <el-checkbox-group v-model="v.task" size="mini">
              <el-checkbox :label="k.taskName" :key="k.taskId" :value="k.taskId"
                           v-for="k in taskTemplateList">{{ k.taskName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-tab-pane>
        </el-tabs>
      </div>
      <span slot="footer">
        <el-button @click="submit" type="info" v-if="optionType=='add'">确定</el-button>
        <el-button @click="edit" type="info" v-if="optionType=='edit'">修改</el-button>
      </span>


    </el-dialog>

    <!--    创建任务弹窗--><!--    创建任务弹窗--><!--    创建任务弹窗--><!--    创建任务弹窗--><!--    创建任务弹窗--><!--    创建任务弹窗-->
    <el-dialog :visible.sync="taskListStatus" title="任务列表"
               width="50%"
               center
               top="10px"
               :show-close="true"
    >
      <div style="display: flex;justify-content: flex-end;align-items: center;margin-bottom:20px">
        <el-input placeholder="请输入内容" v-model="taskName" class="input-with-select" size="small">
          <el-select v-model="type" slot="prepend" placeholder="请选择" style="width: 150px;" @change="changeSupplierType">
            <!--            <el-option label="装修" value="1"></el-option>-->
            <!--            <el-option label="冷链" value="6"></el-option>-->
            <!--            <el-option label="门窗" value="2"></el-option>-->
            <!--            <el-option label="广告" value="3"></el-option>-->
            <!--            <el-option label="货架" value="4"></el-option>-->
            <!--            <el-option label="监控" value="5"></el-option>-->
            <el-option :label="item.name" :value="item.type" :key="index"
                       v-for="(item,index) in taskNameList"></el-option>

          </el-select>
          <el-button slot="append" @click="addTaskName">新增</el-button>
        </el-input>
        <!--        <el-input v-model="taskName" size="small" placeholder="请输入需要添加的任务名称">-->
        <!--          <el-button slot="append" @click="addTaskName">新增</el-button>-->
        <!--        </el-input>-->
      </div>
      <el-table :data="taskTableList" border max-height="600px" :cell-style="{ 'textAlign': 'center' }"
                :header-cell-style="{ 'background-color': '#303e9d', 'color': 'white', 'textAlign': 'center' }">
        <el-table-column prop="taskId" label="任务ID" width="100px"></el-table-column>
        <el-table-column label="任务名称">
          <template slot-scope="scope">
            <div v-if="scope.row.edit==0">{{ scope.row.taskName }}</div>
            <div v-if="scope.row.edit==1">
              <el-input v-model="scope.row.taskName"></el-input>
            </div>

          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="创建时间"></el-table-column>
        <el-table-column prop="userName" label="创建人"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link type="warning" @click="scope.row.edit=1" style="margin-right: 10px" v-if="scope.row.edit==0">修改
            </el-link>
            <el-link type="warning" @click="editTask(scope.row)" style="margin-right: 10px" v-if="scope.row.edit==1">
              确定
            </el-link>
            <el-link type="info" @click="scope.row.edit=0" style="margin-right: 10px" v-if="scope.row.edit==1">取消
            </el-link>
            <el-link type="danger" @click="deleteTask(scope.row.taskId)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import quinn from "../../utils/quinn";
import store from "../../store";

export default {
  name: "createTask",
  meta: {title: "创建任务", icon: "el-icon-s-claim", authorityList: 200, sort: 7},
  data() {
    return {
      templateStatus: false,
      taskListStatus: false,
      params: {
        pageSize: 20,
        pageNumber: 1,
        templateName: "",
        companyName: ""
      },
      day: "",
      loading: false,
      chooseDateIndex: 1,
      currentPage: 1,
      taskNameList: [],
      brandList: [],
      totalCount: 0,
      title: "",
      templateName: "",
      activeName: '第1个任务',
      optionType: "",
      dataList: [],
      taskTableList: [],
      taskTemplateList: [],
      taskName: '',
      tagName: '',
      type: 1,
      taskInfo: [],
      authorityList: [],
      templateCreateInfo: [
        {
          'name': '第1个任务',
          "task": [],
        },
      ]
    }

  },
  computed: {
    typeMap() {
      return {
        1: '装修',
        2: '冷链',
        3: '货架',
        4: '监控',
        5: '门窗、收银台',
        6: '广告',
      };
    }
  },
  created() {
    this.getBrand()
    this.getBrand()
    const {authorityList = []} = quinn.getStorage("userDatav3") || store.state.userData || {};
    this.authorityList = authorityList
  },
  methods: {
    getBrand() {
      this.$api.storeGetBrandPartyList().then(res => {
        this.brandList = res
        this.params.brandPartyId = res[0].id
        this.getModules()
      })
    },
    chooseType(val) {
      this.chooseDateIndex = val
      this.type = val
      this.getTask()
      this.createdTemplate()
    },
    changeSupplierType(val) {
      this.type = val
      this.getTask()
    },
    _reset() {
      this.params = this.$options.data.call(this).params
    },
    getModules() {
      this.loading = true
      const params = this.params
      this.$api.templateGetTaskTemplateList(params).then(res => {
        this.dataList = res.data
        this.totalCount = res.total
        this.loading = false
      })
    },
    getTask() {
      this.$api.taskGetTaskList({supplierType: this.type}).then(res => {
            res.map(el => {
              el.edit = 0
            })
            this.taskTableList = res;
          }
      )
    },
    handleClick(tab, event) {
    },
    async createdTemplate() {
      this.title = '创建'
      this.optionType = 'add'
      this.type = this.chooseDateIndex
      this.activeName = '第1个任务'
      this.templateName = ""
      this.day = ""
      this.templateCreateInfo = [
        {
          'name': '第1个任务',
          "task": [],
        },
      ]
      const res = await this.$api.taskGetTaskList({supplierType: this.type})
      this.taskTemplateList = res
      this.$api.budgetGetSupplierTypeVo({brandPartyId:this.params.brandPartyId}).then(res => {
        this.taskNameList = res
      })
      this.templateStatus = true
    },
    async pasteModules() {
      let data = JSON.parse(sessionStorage.getItem('modules'))
      if (!data) return this.$message.warning('空')
      this.templateName = data.templateName
      this.day = data.day
      const res = await this.$api.taskGetTaskList({supplierType: this.type})
      this.taskTemplateList = res
      this.templateCreateInfo = data.taskList
      this.templateCreateInfo.map(el => {
        el.task = el.task.map(task => task.taskName);
      })
      // console.log(this.templateCreateInfo)
    },
    deleteDate(i) {
      // console.log(i)
      this.templateCreateInfo.splice(i, 1)
      this.activeName = '第1个任务'
      this.templateCreateInfo.map((el, i) => {
        el.name = '第' + (i + 1) + '个任务'
      })
      //  删除下标i后  tabs的name排序未解决
    },
    taskListDialog() {
      this.taskListStatus = true;
      this.type = 1
      this.taskName = ''
      this.$api.budgetGetSupplierTypeVo({brandPartyId:this.params.brandPartyId}).then(res => {
        this.taskNameList = res
      })
      this.getTask()

    },
    deleteTask(id) {
      let params = {
        taskId: id,
        state: 0
      }
      this.$api.taskUpdateTaskList(params).then(res => {
        if (res == 1) {
          this.$message({message: "删除成功！", type: "danger"})
          this.getTask();
        }
        this.getTask();
      })
    },
    addTaskName() {
      if (!this.taskName || !this.type) return this.$message.warning('请选择类型或填写任务名称！')
      let data = {
        taskName: this.taskName,
        supplierType: this.type
      }
      this.$api.taskAddTaskList(data).then(res => {
        if (res == 1) {
          this.$message({message: "添加成功！", type: "success"})
          this.getTask();
        }
      })
    },
    async addTemplateName(val) {
      this.activeName = '第' + (val.length + 1) + '个任务'
      const res = await this.$api.taskGetTaskList({supplierType: this.type})
      this.templateCreateInfo.push({
        'name': '第' + (val.length + 1) + '个任务',
        "task": [],
      })
      this.taskTemplateList = res
    },
    async submit() {
      if (!this.templateName) return this.$message.warning("模板名称不能为空！")
      if (this.day === '' || !/^[1-9]\d*$/.test(this.day)) {
        return this.$message.warning("任务周期不能为空且必须为正整数！");
      }
      const res = await this.$api.taskGetTaskList({supplierType: this.type})
      this.templateCreateInfo.map((el, index) => {
        el.task = res.filter(res => el.task.includes(res.taskName))
        el.today = index + 1
        el.task.map(i => {
          i.ok = 0
          i.images = []
          const toDelete = ['createTime', 'userName', "state", 'updateTime'];
          toDelete.forEach(prop => delete i[prop]);
        })
      })
      const data = {
        templateName: this.templateName,
        day: this.day,
        taskList: this.templateCreateInfo,
        supplierType: this.type,
      }
      this.$api.templateAddTaskTemplate(data).then(res => {
        if (res == 1) {
          this.$message({message: "添加成功！", type: "success"})
          this.templateStatus = false
          this.getModules()
        }
      })
    },
    editTask(row) {
      const data = {
        taskId: row.taskId,
        taskName: row.taskName,
        supplierType: this.type,
        state: 1
      }
      this.$api.taskUpdateTaskList(data).then(res => {
        if (res == 1) {
          this.$message({message: "修改成功！", type: "success"})
          this.getTask();
        }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getModules()
    },
    handleCurrentChange(val) {
      this.pageNumber = val
      this.getModules()
    },
    async editModules(row) {
      this.title = '编辑'
      this.type = row.supplierType
      this.chooseDateIndex = row.supplierType
      const editRow = JSON.parse(JSON.stringify(row));
      this.optionType = "edit"
      this.templateStatus = true
      this.templateName = editRow.templateName
      this.day = editRow.day
      this.templateId = editRow.templateId
      const res = await this.$api.taskGetTaskList({supplierType: this.type})
      this.taskTemplateList = res
      this.templateCreateInfo = editRow.taskList
      this.templateCreateInfo.map(el => {
        el.task = el.task.map(task => task.taskName);
      })
    },
    copyModules(row) {
      sessionStorage.setItem('modules', JSON.stringify(row))
      let data = sessionStorage.getItem('modules')
      if (data) return this.$message.success('复制成功!')
    },
    async edit() {
      const res = await this.$api.taskGetTaskList({supplierType: this.type})
      const templateCreateInfo = JSON.parse(JSON.stringify(this.templateCreateInfo));
      templateCreateInfo.map((el, index) => {
        el.task = res.filter(res => el.task.includes(res.taskName))
        el.today = index + 1
        el.task.map(i => {
          i.ok = 0
          i.images = []
          const toDelete = ['createTime', 'userName', "state", 'updateTime'];
          toDelete.forEach(prop => delete i[prop]);
        })
      })
      let taskList = templateCreateInfo.filter(day => day.task.length > 0);
      if (!this.templateName) return this.$message.warning("模板名称不能为空！")
      if (this.day === '' || !/^[1-9]\d*$/.test(this.day)) {
        return this.$message.warning("任务周期不能为空且必须为正整数！");
      }
      const data = {
        templateName: this.templateName,
        day: this.day,
        taskList: taskList,
        templateId: this.templateId,
        state: 1
      }
      this.$api.templateUpdateTemplate(data).then(res => {
        if (res == 1) {
          this.$message({message: "修改成功！", type: "success"})
          this.templateStatus = false
          this.getModules();
        }
      })

    }
  }
}
</script>
<style lang="less" scoped>
@import "../../assets/css/public.css";

/deep/ .el-select {
  background-color: #F3F6FD;
  border: 1px solid #F3F6FD;
  height: 20px;
}

/depp/ .el-icon-arrow-right:before {
  font-size: 23px;
}

.typeList {
  width: 100px;
  height: 40px;
  color: #000000;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  background: linear-gradient(to left, #b3d8ff, #b3d8ff) left top no-repeat,
  linear-gradient(to bottom, #b3d8ff, #b3d8ff) left top no-repeat,
  linear-gradient(to left, #b3d8ff, #b3d8ff) right top no-repeat,
  linear-gradient(to bottom, #b3d8ff, #b3d8ff) right top no-repeat,
  linear-gradient(to left, #b3d8ff, #b3d8ff) left bottom no-repeat,
  linear-gradient(to bottom, #b3d8ff, #b3d8ff) left bottom no-repeat,
  linear-gradient(to left, #b3d8ff, #b3d8ff) right bottom no-repeat,
  linear-gradient(to left, #b3d8ff, #b3d8ff) right bottom no-repeat;
  background-size: 1px 20px, 20px 1px, 1px 20px, 20px 1px;

  span {
    cursor: default;
  }
}

.active {
  box-shadow: inset 0 0 16px 0 #66b1ff;
  font-size: 16px;
  font-weight: bolder;
}
</style>